﻿using Common;
using GerberLibrary.Core;
using GerberLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using UserControl = System.Windows.Controls.UserControl;

namespace WpfCommCtl.Controls
{
    /// <summary>
    /// ImportGerber.xaml 的交互逻辑
    /// </summary>
    public partial class ImportGerber : UserControl
    {
        ImportGerberViewModel viewModel;

        /// <summary>
        /// ctor
        /// </summary>
        public ImportGerber()
        {
            InitializeComponent();
            viewModel = new ImportGerberViewModel();
            this.DataContext = viewModel;
        }

        private Action<ImportGerberResult> importGerberReturn = null;

        /// <summary>
        /// 导入gerber返回
        /// </summary>
        public Action<ImportGerberResult> ImportGerberReturn
        {
            get { return importGerberReturn; }
            set
            {
                if (value is not null)
                {
                    if (viewModel.ImportGerberReturn is null)
                    {
                        viewModel.ImportGerberReturn = value;
                    }
                }
            }
        }

        private void btnSelectDirectory_Click(object sender, RoutedEventArgs e)
        {
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = Visibility.Collapsed;
        }
    }

    /// <summary>
    /// Gerber图片类型
    /// </summary>
    public enum GerberImageType
    {
        /// <summary>
        /// 上表面
        /// </summary>
        Top,

        /// <summary>
        /// 下表面
        /// </summary>
        Bottom
    }

    /// <summary>
    /// gerber文件解析返回结果
    /// </summary>
    public class ImportGerberResult
    {
        /// <summary>
        /// gerber图片
        /// </summary>
        public Bitmap Bmp;

        /// <summary>
        /// 长度
        /// </summary>
        public double Width;

        /// <summary>
        /// 宽度
        /// </summary>
        public double Height;
    }

    /// <summary>
    /// gerber工具类
    /// </summary>
    public class GerberTool
    {
        /// <summary>
        /// 传入gerber文件目录输出PCB图片及尺寸
        /// </summary>
        /// <param name="path">   </param>
        /// <param name="width">  </param>
        /// <param name="height"> </param>
        /// <param name="type">   </param>
        /// <returns> </returns>
        /// <exception cref="DirectoryNotFoundException"> </exception>
        /// <exception cref="Exception"> </exception>
        public static Bitmap GetPcbImage(in string path, out double width, out double height, GerberImageType type = GerberImageType.Top)
        {
            int dpi = 400;
            string pcbcolor = "green";
            string silkcolor = "white";
            string tracecolor = "auto";
            string coppercolor = "gold";
            //string path = @"C:\Users\1\Documents\WeChat Files\wxid_ubwim7xg6mqm21\FileStorage\File\2022-11\T00007-QEB000442_V1.0_GERBER\T00007-QEB000442_V1.0_GERBER";
            //string path = @"C:\Users\1\Documents\WeChat Files\wxid_ubwim7xg6mqm21\FileStorage\File\2022-11\JQ6030-QEB000333 V1.9钢网\JQ6030-QEB000333 V1.9钢网";
            List<string> RestList = new List<string>();

            Gerber.SaveIntermediateImages = false;  //保存中间图片
            Gerber.ShowProgress = false;    //显示操作步骤
            GerberImageCreator GIC = new GerberImageCreator();

            List<String> FileList = new List<string>();

            if (Directory.Exists(path))
            {
                FileList.AddRange(Directory.GetFiles(path, "*.*"));
            }
            else
            {
                //throw new DirectoryNotFoundException(Languages.GetResourceDictionary("Exception_40"));
                throw new DirectoryNotFoundException("路径不存在");
            }

            if (FileList.Count == 0)
            {
                //throw new DirectoryNotFoundException(Languages.GetResourceDictionary("Exception_41"));
                throw new DirectoryNotFoundException("路径下不存在文件");
            }

            GIC.AddBoardsToSet(FileList, new StandardConsoleLog(), true);

            var box = GIC.BoundingBox;
            width = Math.Round(box.BottomRight.X - box.TopLeft.X, 2);
            height = Math.Round(box.BottomRight.Y - box.TopLeft.Y, 2);

            if (width <= 0 || height <= 0)
            {
                //throw new Exception(Languages.GetResourceDictionary("Exception_42"));
                throw new Exception("Gerber对象长度或高度为负值");
            }

            BoardRenderColorSet colors = new BoardRenderColorSet();
            colors.SetupColors(pcbcolor, silkcolor, tracecolor, coppercolor);
            GIC.SetColors(colors);

            BoardSide side = type == GerberImageType.Top ? BoardSide.Top : BoardSide.Bottom;
            Bitmap B = GIC.DrawBoard(dpi, side, colors);

            return B;
        }
    }

    /// <summary>
    /// ViewModel
    /// </summary>
    internal class ImportGerberViewModel : NotifyBase
    {
        private string _gerberPath;

        public string GerberPath
        {
            get { return _gerberPath; }
            set
            {
                _gerberPath = value;
                this.DoNotify();
            }
        }

        private GerberImageType _gerberType;

        public GerberImageType GerberType
        {
            get { return _gerberType; }
            set
            {
                _gerberType = value;
                this.DoNotify();
            }
        }

        private string _errMsg;

        public string ErrMsg
        {
            get { return _errMsg; }
            set
            {
                _errMsg = value;
                this.DoNotify();
            }
        }

        public CommandBase SelectDirectoryCommand { get; set; }
        public CommandBase ImportGerberFilesCommand { get; set; }

        public Action<ImportGerberResult> ImportGerberReturn;

        public ImportGerberViewModel()
        {
            SelectDirectoryCommand = new CommandBase(SelectDirectory);
            ImportGerberFilesCommand = new CommandBase(ImportGerberFiles);
        }

        private void ImportGerberFiles(object obj)
        {
            try
            {
                Task.Factory.StartNew(() =>
                {
                    ErrMsg = "正在导入";
                    Task<ImportGerberResult> task = Task.Run(() =>
                    {
                        ImportGerberResult result = new ImportGerberResult();
                        result.Bmp = GerberTool.GetPcbImage(GerberPath, out result.Width, out result.Height, GerberType);
                        return result;
                    });
                    task.ContinueWith(_ =>
                    {
                        if (task.Exception is null)
                        {
                            ImportGerberReturn?.Invoke(task.Result);

                            //Application.Current.Dispatcher.Invoke(() =>
                            //{
                            //    CurrentPCBInfo.Width = task.Result.Width;
                            //    CurrentPCBInfo.Height = task.Result.Height;
                            //    CurrentPCBInfo.PcbImage = task.Result.Bmp;

                            //    task.Result.Bmp?.Save(Environment.CurrentDirectory + @"\bmps\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bmp");
                            //    ImportGerberError = "";
                            //    ImportGerberBorderVisbility = Visibility.Collapsed;
                            //});
                            if (!Directory.Exists(Environment.CurrentDirectory + @"\bmps\"))
                            {
                                Directory.CreateDirectory(Environment.CurrentDirectory + @"\bmps\");
                            }
                            task.Result.Bmp?.Save(Environment.CurrentDirectory + @"\bmps\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bmp");
                            ErrMsg = "导入成功";
                        }
                        else
                        {
                            ErrMsg = task.Exception.InnerException.Message;
                        }
                    }).ContinueWith(_ =>
                    {
                        if (_.Exception is not null)
                        {
                            ErrMsg = _.Exception.InnerException.Message;
                        }
                    });
                });
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
            }
        }

        private void SelectDirectory(object obj)
        {
            try
            {
                var dialog = new FolderBrowserDialog()
                {
                    RootFolder = Environment.SpecialFolder.Desktop,
                    Description = "选择一个目录",
                    ShowNewFolderButton = true,
                };

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    GerberPath = dialog.SelectedPath;
                    // 处理选择的目录
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}